<template>
	<form class='loginView' ref="ReginForm">
		<view class="header">
			<image src="../../static/img/logo.png"></image>
		</view>
		<view class="login-mian" style="padding-top: 200px;box-sizing: border-box;">
			<view class="login-name">
				<text>绑定账号密码登录</text>
			</view>

			<view class="phone">
				<view class="phone-head center-algin">
					<text class="head">账号</text>
					<input class="input" maxlength="11" v-model="username" placeholder="请输入账号" />
				</view>
			</view>

			<view class="phone pws">
				<view class="phone-head center-algin">
					<text class="head">密码</text>
					<input class="input" maxlength="11" v-model="password" placeholder="请输入密码" />
				</view>
			</view>
			<button type="default" class="loginbutton log" hover-class="hover" formType="submit"
				@click="getUserInfo">确认绑定</button>
		</view>
	</form>
</template>

<script>
import WebSocketClass from '@/config/websocket.js';

export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },

  methods: {
    async getUserInfo() {
      try {
        let param = { username: this.username, password: this.password };
        console.log("请求参数", param);

        // 登录接口
        let res = await this.$apis.login(param);
        console.log("登录返回", res);
        this.$store.commit("SET_TOKEN", res.data.access_token);

        // 获取用户信息
        let userInfo = await this.$apis.getUserInfo();
        console.log("用户信息", userInfo);
        this.$store.commit("SET_USERINFO", userInfo.data);

        if (userInfo) {
          uni.showToast({ title: "登录成功", icon: "success", duration: 2000 });

          // 🌟 创建 WebSocket 实例并建立连接
          const userId = userInfo.data.id;
          const socketUrl = `ws://localhost:5000/cloudBusiness/ws/message/${userId}`;
		  console.log("socketUrl",socketUrl)
          const wsInstance = new WebSocketClass(socketUrl);

          // 🌟 挂载 WebSocket 实例到 Vue 原型，方便全局调用
          this.$ws = wsInstance;
		  //获取消息
		  wsInstance.sendMsg({type:"token"});
          // 🌟 监听 WebSocket 消息
          wsInstance.getMsg((res) => {
            console.log("接收到消息", res);
            uni.showToast({ title: `新消息: ${res.msg}`, icon: "none" });
          });


          setTimeout(() => {
            uni.reLaunch({ url: "/pages/user/user" });
          }, 1000);
        }
      } catch (e) {
        console.error("登录失败", e);
        uni.showToast({ title: "登录失败", icon: "error", duration: 2000 });
      }
    },

    // 登出时关闭 WebSocket
    logout() {
      if (this.$ws) this.$ws.closeSocket();
      uni.removeStorageSync('token');
      uni.reLaunch({ url: "/pages/login/login" });
    }
  },

  // 页面销毁时自动关闭 WebSocket
  // onUnload() {
  //   if (this.$ws) this.$ws.closeSocket();
  // }
};
</script>

<style>
	/* 登录页面的样式 */
	.loginView {
		height: calc(100vh);
		width: 100%;
	}

	.header {
		margin: 10upx 0 10upx 0;
		border-bottom: 1px solid #eee;
		text-align: center;
		width: 100%;
		height: 300rpx;
		line-height: 450rpx;
	}

	.login-mian {
		width: 90%;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		margin: 0 auto;
	}

	.login-name {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-top: 40rpx;
	}

	.phone {
		margin-top: 40rpx;
	}

	.phone-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #ddd;
		padding: 10rpx 0;
	}

	.phone-head .head {
		font-size: 16px;
		color: #333;
	}

	.phone-head .input {
		flex: 1;
		margin-left: 10rpx;
		font-size: 16px;
		color: #333;
		text-align: right;
	}

	.loginbutton {
		width: 100%;
		background-color: #007aff;
		color: #fff;
		font-size: 16px;
		padding: 20rpx 0;
		border-radius: 5rpx;
		margin-top: 40rpx;
		border: none;
		outline: none;
		display: block;
	}

	.loginbutton:hover {
		background-color: #0056b3;
	}

	.hover {
		background-color: #0056b3;
	}
</style>